<template>
  <div class="form-container">
    <div class="form-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>活动管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/activityGoodsList' }"
          >活动商品</el-breadcrumb-item
        >
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="form-content" style="background: #fff">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="126px"
        v-if="activeName == '1'"
      >
        <!-- <el-form-item label="文章分类" prop="type_id">
          <el-cascader
            ref="organizerUnit"
            @change="handleParentType"
            :options="types"
            v-model="form.type_id"
            :show-all-levels="false"
            clearable
            :props="{checkStrictly:true,emitPath:false}"
            placeholder="请选择商品分类"></el-cascader>
        </el-form-item> -->

        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>

        <el-form-item label="子标题" prop="sub_name">
          <el-input
            v-model="form.sub_name"
            placeholder="请输入子标题"
          ></el-input>
        </el-form-item>

        <el-form-item label="商品单价" prop="price">
          <el-input
            v-model="form.price"
            placeholder="请输入商品单价"
          ></el-input>
        </el-form-item>

        <el-form-item label="商品库存" prop="stock">
          <el-input
            v-model="form.stock"
            placeholder="请输入商品库存"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio v-model="form.status" label="1">开启</el-radio>
          <el-radio v-model="form.status" label="0">关闭</el-radio>
        </el-form-item>

        <el-form-item label="商品类型">
          <!-- <el-radio v-model="form.type" label="1">实物</el-radio> -->
          <el-radio v-model="form.type" label="2">虚拟商品</el-radio>
        </el-form-item>

        <el-form-item label="商品主图">
          <el-upload
            action="/api/client/base/uploadfile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            ref="upload"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="true"
            :limit="1"
            :headers="myHeaders"
            :file-list="fileList"
            accept="image/jpeg, image/jpg, image/gif, image/png"
            :multiple="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="排序">
          <el-col :span="5">
            <el-input
              v-model="form.sort"
              placeholder="数字越大越靠后"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="活动说明">
          <VueEditor
            style="width: 100%"
            v-loading="editorLoading"
            element-loading-text="图片上传中"
            element-loading-background="rgba(0, 0, 0, 0.5)"
            useCustomImageHandler
            @image-added="handleImageAdded"
            :editorToolbar="customToolbar"
            v-model="form.remark"
          />
          <!-- <el-input type="textarea" v-model="form.remark" rows="3"></el-input> -->
        </el-form-item>
        <el-form-item label="配置礼品包">
          <shop-table
            ref="shopFn"
            :prizeList="form.prizes"
            @listenChild="listenPrize"
          ></shop-table>
        </el-form-item>

        <el-form-item>
          <el-row>
            <el-button type="danger" @click="confirmAdd('form')"
              >立即保存</el-button
            >
            <el-button type="default" @click="cancel()">返回</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
import shopTable from "@/components/activity/elevenActivity/activityGoods/publicTable/shopList.vue";
export default {
  components: {
    VueEditor,
    shopTable,
  },
  name: "Vue2Editor",
  data() {
    return {
      validate: false,
      activeName: "first",
      types: [],
      form: {
        name: "",
        sub_name: "",
        img: "",
        price: "",
        status: "0",
        stock: "",
        type: "2",
        rel_id: "",
        sort: 100,
        remark: "",
      },
      videoUrl: "", //视频连接
      videoId: "", //视频id
      videoFlag: false,
      videoUploadPercent: 0,
      dialogVisible: false,
      replaceList: [],
      prizeList: [],

      rules: {
        //   type_id: [
        //     {required: true, message: '请选择文章分类', trigger: 'blur'}
        //   ],
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        price: [{ required: true, message: "请输入商品单价", trigger: "blur" }],
        stock: [{ required: true, message: "请输入商品库存", trigger: "blur" }],
      },
      filter_keyword: "",
      editorLoading: false, //富文本图片loading
      customToolbar: [
        [{ header: [false, 1, 2, 3, 4, 5, 6] }], //标题
        ["bold", "italic", "underline", "strike"], //加粗\斜体\下划线\作废
        ["blockquote", "code-block"],
        [
          {
            script: "sub",
          },
          {
            script: "super",
          },
        ], // superscript/subscript
        [
          {
            indent: "-1",
          },
          {
            indent: "+1",
          },
        ], // outdent/indent
        [
          {
            direction: "rtl",
          },
        ],
        [{ align: "" }, { align: "center" }, { align: "right" }], //对齐
        [{ list: "ordered" }, { list: "bullet" }, { list: "check" }], //有序无序列表
        [{ background: [] }, { color: [] }], //背景色
        ["image", "link"], //图片、链接
        ["clean"], //清楚格式（所谓去掉背景色这些花里胡巧）
        ["code"], //代码
        ["code-block"], //代码块
        //['video'] //视频
      ],
      fileList_bg: [],
      dialogImageUrl_bg: "",
      dialogVisible_bg: false,

      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      myHeaders: {
        "access-token": this.$store.state.token, //这里重新定义了请求头
        Authorization: this.$store.state.token,
        "user-id": this.$store.state.user_id,
      },

      valueTime: [],
      id: "",
      // code:''
      activeName: "1",
    };
  },
  mounted() {
    this.id = this.$route.query.id;
    // this.code = this.$route.query.code;
    if (this.id) {
      this.getActivityDetail();
    }
    //   this.loadTypes();
  },
  methods: {
    // 获取商品详情
    getActivityDetail() {
      this.$http
        .post("/api/root/activity/good/detail", { id: this.id })
        .then((res) => {
          console.log(res, "商品详情");
          // if(res.code==1){
          this.form = { ...res.data };
          this.form.status = res.data.status == 1 ? "1" : "0";
          this.form.type = res.data.type.toString();
          if (res.data.start_at) {
            let startTime = this.$moment(res.data.start_at * 1000).format(
              "yyyy-MM-DD HH:mm:ss"
            );
            let endTime = this.$moment(res.data.end_at * 1000).format(
              "yyyy-MM-DD HH:mm:ss"
            );
            this.form.start_at = startTime;
            this.form.end_at = endTime;
            this.valueTime = [startTime, endTime];
          }

          // 主图
          if (res.data.img.length > 0) {
            res.data.img.map((item) => {
              this.fileList.push({
                url: item.path,
                id: item.id,
              });
            });
          }

          // }
        });
    },

    // 颜色选择器
    handleChangeColor(val) {
      console.log("输出颜色值", val); // 颜色 #6c8198
      this.form.back_color = val;
    },

    // 监听子组件选择的奖品
    listenPrize(data) {
      let arr = [];
      if (data.length) {
        data.map((item) => {
          arr.push(item.id);
        });
      }
      this.form.rel_id = arr.join(",");
    },

    // 选择时间
    selectTime() {
      console.log(this.valueTime, "----");
      if (this.valueTime) {
        this.form.start_at = this.$moment(this.valueTime[0]).format(
          "yyyy-MM-DD HH:mm:ss"
        );
        this.form.end_at = this.$moment(this.valueTime[1]).format(
          "yyyy-MM-DD HH:mm:ss"
        );
      }
      console.log(this.form, "000");
    },

    // 背景图
    handleRemove_bg(file, fileList) {
      this.fileList_bg = fileList;
    },
    handlePictureCardPreview_bg(file) {
      console.log("file", file);
      this.dialogImageUrl_bg = file.url;
      this.dialogVisible_bg = true;
    },
    handleAvatarSuccess_bg(res, file, fileList) {
      console.log("fileList", fileList);
      this.fileList_bg = fileList;
    },
    beforeAvatarUpload_bg(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 10MB!");
      }
      return isLt2M;
    },

    //   主图
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
      console.log("file", file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file, fileList) {
      console.log("fileList", fileList);
      this.fileList = fileList;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 10MB!");
      }
      return isLt2M;
    },

    // 验证视频格式
    beforeUploadVideo(file) {
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
        ].indexOf(file.type) === -1
      ) {
        this.$message.error("请上传正确的视频格式");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 30;
      if (!isLt2M) {
        this.$message.error("上传视频大小不能超过 30MB!");
      }
    },
    // 上传进度显示
    uploadVideoProcess(event, file, fileList) {
      console.log(event.percent, file, fileList);
      this.videoFlag = true;
      this.videoUploadPercent = Math.floor(event.percent);
    },

    // 获取上传地址
    handleVideoSuccess(res, file) {
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      console.log(res, file, "视频上传");
      this.videoUrl = file.response.data.url;
      this.videoId = file.response.data.id;
    },

    // 删除视频按钮
    closeVideo() {
      this.videoUrl = "";
      this.videoId = "";
    },
    confirmAdd(form) {
      this.validateFormData(form);
      if (this.validate) {
        const _ths = this;

        //   主图
        let imgArr = [];
        if (this.fileList.length > 0) {
          this.fileList.map((v) => {
            if (v.response) {
              imgArr.push(v.response.data.id);
            } else {
              imgArr.push(v.id);
            }
          });
        }
        this.form.img = imgArr.join(",");
        this.form.id = this.id;
        console.log(JSON.stringify(this.form), "000");
        let url = this.id
          ? "/api/root/activity/good/edit"
          : "/api/root/activity/good/add";
        this.$http.post(url, { ...this.form }).then((rest) => {
          if (rest.code == 1) {
            this.$message.success(this.id ? "修改成功" : "添加成功");
            setTimeout(function () {
              _ths.$router.back(1);
            }, 800);
          } else {
            this.form = {
              ...this.form,
            };
            this.$message.error(rest.msg);
          }
        });
      }
    },
    cancel() {
      this.$router.back(1);
    },

    /**
     * 验证表单数据
     * @param form
     */
    validateFormData(form) {
      this.$refs[form].validate((valid) => {
        if (!valid) {
          this.$message({
            message: "表单数据未填写完整,操作失败！",
            type: "warning",
          });
          return false;
        }
        this.validate = true;
        return true;
      });
    },
    //富文本上传图片
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      var formData = new FormData();
      let isLtSize = file.size / 1024 / 1024 < 10;
      if (!isLtSize) {
        this.$message.warning("上传文件不能超过 10MB!");
        return;
      }
      this.editorLoading = true;
      formData.append("file", file);
      this.$http
        .post("/api/admin/base/uploadfile", formData)
        .then((result) => {
          if (result.msg !== "ok" || !result.data) {
            this.$message.error(result.msg);
            this.editorLoading = false;
            resetUploader();
            return false;
          }
          // 你上传路径返回的url
          let url = result.data.url;
          if (file.type === "video/mp4") {
            Editor.insertEmbed(cursorLocation, "video", url); //视频
          } else if (file.type === "audio/mpeg") {
            Editor.insertEmbed(cursorLocation, "video", url); //音频
          } else {
            Editor.insertEmbed(cursorLocation, "image", url);
          }
          resetUploader();
          this.editorLoading = false;
        })
        .catch((err) => {
          this.editorLoading = false;
        });
    },
    //   loadTypes() {
    //     var _ths = this;
    //     this.$http.post('/api/root/article/articleTypes', {})
    //       .then((rest) => {
    //         if (rest.data.length > 0) {
    //           _ths.types = rest.data;
    //         }
    //       })
    //   },
    handleParentType(value) {
      this.form.pid = value;
      if (this.$refs.organizerUnit) {
        this.$refs.organizerUnit.dropDownVisible = false;
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import "index.less";
</style>